package com.itcms.webservice.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.jws.WebService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.itcms.common.util.DateUtil;
import com.itcms.common.util.JacksonMapper;
import com.itcms.core.constant.Constants;
import com.itcms.core.domain.Attachment;
import com.itcms.core.domain.Info;
import com.itcms.core.domain.InfoDetail;
import com.itcms.core.domain.InfoFile;
import com.itcms.core.domain.InfoImage;
import com.itcms.core.domain.Node;
import com.itcms.core.service.AttachmentRefService;
import com.itcms.core.service.AttachmentService;
import com.itcms.core.service.InfoService;
import com.itcms.core.service.NodeQueryService;
import com.itcms.core.service.OperationLogService;
import com.itcms.core.service.OrgService;
import com.itcms.core.service.SiteService;
import com.itcms.core.service.UserService;
import com.itcms.ext.domain.OANode;
import com.itcms.ext.service.OANodeService;
import com.itcms.webservice.InfopubService;
import com.itcms.webservice.domain.AttachVO;
import com.itcms.webservice.domain.InfoExt;
import com.itcms.webservice.domain.NodeVo;
import com.itcms.webservice.domain.Person;

@WebService(endpointInterface="com.itcms.webservice.InfopubService",serviceName="infopubService")
public class InfopubServiceImp implements InfopubService {
	private static final Logger logger = LoggerFactory
			.getLogger(InfopubServiceImp.class);

	public String getCategoryJson(String pwd) {
		if(!pwd.equals("gdjt2010")){
			Map<String, Object> map = new HashMap<>();
			map.put("error", "信息密码错误！");
			map.put("success", false);
			return JacksonMapper.toJson(map);
		}else{
			try {
				return JacksonMapper.toJson(OANodeList());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public String infoSave(com.itcms.webservice.domain.Info info, String pwd){
		Map<String, Object> map = null;
		if(!pwd.equals("gdjt2010")){
			map = new HashMap<>();
			map.put("infoid", null);
			map.put("error", "信息密码错误！");
			map.put("success", false);
		}else{
			try {
				map = new HashMap<>();
				map.put("infoid", setValue(info).getId());
				map.put("success", true);
				map.put("error", null);
			} catch (Exception e) {
				map = new HashMap<>();
				map.put("error", e);
				map.put("success", false);
				map.put("error", null);
				e.printStackTrace();
			}
		}
		return JacksonMapper.toJson(map);
	}
	
	public String customsSave(InfoExt info, String pwd){
		Map<String, Object> map = null;
		if(!pwd.equals("gdjt2010")){
			map = new HashMap<>();
			map.put("infoid", null);
			map.put("error", "信息密码错误！");
			map.put("success", false);
		}else{
			try {
				map = new HashMap<>();
				map.put("infoid", setCustomsValue(info).getId());
				map.put("success", true);
				map.put("error", null);
			} catch (Exception e) {
				map = new HashMap<>();
				map.put("error", e);
				map.put("success", false);
				map.put("error", null);
				e.printStackTrace();
			}
		}
		return JacksonMapper.toJson(map);
	}
	/*public String getCategoryJson(String pwd) {
		if(!pwd.equals("gdjt2010")){
			ReturnObj<String> returnObj =  new ReturnObj("信息密码错误！");
			return JacksonMapper.toJson(returnObj);
		}else{
			try {
				ReturnObj<List<NodeVo>> returnObj = new ReturnObj<List<NodeVo>>(OANodeList());
				return JacksonMapper.toJson(returnObj);
			} catch (Exception e) {
				e.printStackTrace();
				ReturnObj<List<NodeVo>> returnObj = new ReturnObj<List<NodeVo>>(e);
				return JacksonMapper.toJson(returnObj);
			}
		}
	}*/

	public List<NodeVo> nodeList() {
		// TODO Auto-generated method stub
		List<NodeVo> nodeList = new ArrayList<NodeVo>();
		Integer queryParentId=99;
		Integer siteId = 5;
		Node parent = null;
		if (queryParentId != null) {
			parent = query.get(queryParentId);
		}
		if (parent == null) {
			parent = query.findRoot(siteId);
			if (parent != null) {
				queryParentId = parent.getId();
			}
		}
		List<Node> list = query.findList(siteId, queryParentId);
		for (Node node : list) {
			NodeVo nodeVo = new NodeVo();
			Integer cateId = node.getId();
			Integer leve = node.getTreeLevel();
			Integer cateParentId;
			if(leve==0){
				cateParentId=null;
			}else{
				cateParentId = node.getParent().getId();
			}
			
			String cateName = node.getName();
			nodeVo.setCateId(cateId.toString());
			nodeVo.setCateName(cateName);
			nodeVo.setCateParentId(cateParentId.toString());
			nodeVo.setLeve(leve.toString());
			nodeList.add(nodeVo);
		}
		return nodeList;
	}
	
	/**
	 * 推送到OA栏目权限
	 * @return
	 */
	public List<NodeVo> OANodeList() {
		// TODO Auto-generated method stub
		List<NodeVo> nodeList = new ArrayList<NodeVo>();
		List<OANode> oaNodes = oaNodeService.findAll();
		for (OANode oaNode : oaNodes) {
			Node node = oaNode.getNode();
			NodeVo nodeVo = new NodeVo();
			Integer cateId = node.getId();
			Integer leve = node.getTreeLevel();
			Integer cateParentId;
			if(leve==0){
				cateParentId=null;
			}else{
				cateParentId = node.getParent().getId();
			}
			
			String cateName = node.getName();
			nodeVo.setCateId(cateId.toString());
			nodeVo.setCateName(cateName);
			String cateParentIdString = null;
			if(!org.springframework.util.StringUtils.isEmpty(cateParentId)){
				cateParentIdString = cateParentId.toString();
			}
			nodeVo.setCateParentId(cateParentIdString);
			nodeVo.setLeve(leve.toString());
			nodeList.add(nodeVo);
		}
		return nodeList;
	}
	
/*	public String infosave(com.itcms.webservice.domain.Info info, String pwd){
		if(!pwd.equals("gdjt2010")){
			ReturnObj<String> returnObj =  new ReturnObj("信息密码错误！");
			return JacksonMapper.toJson(returnObj);
		}else{
			try {
				ReturnObj returnObj = new ReturnObj(setValue(info).getId());
				return JacksonMapper.toJson(returnObj);
			} catch (Exception e) {
				e.printStackTrace();
				ReturnObj returnObj = new ReturnObj(e);
				return JacksonMapper.toJson(returnObj);
			}
		}
	}
*/	
	private Info setValue(com.itcms.webservice.domain.Info info) {
		String cateID = info.getCateID();
		String subCateIDs = info.getSubCateID();
		String content = info.getContent();
		String expDateStr = info.getExpDate();
//		String filesJsoin = info.getFilesJsoin();
//		String lastUpdateDate = info.getLastUpdateDate();
//		String lastUpdateUserId = info.getLastUpdateUserId();
//		String lastUpdateUserName = info.getLastUpdateUserName();
		String publishedTime = info.getPublishedTime();
//		String siteID = info.getSiteID();
//		String source = info.getSource();
//		String subTitle = info.getSubTitle();
//		String templateId = info.getTemplateId();
//		String title = info.getTitle();
//		String type = info.getType();
//		String url = info.getUrl();
//		String writeDate = info.getWriteDate();
//		String writer = info.getWriter();
//		String writerName = info.getWriterName();
		String filesJson = info.getFilesJsoin();
		Info cmsInfo = new Info();
		if(!StringUtils.isBlank(publishedTime) && !publishedTime.equals("?")){
			Date publishDate = DateUtil.getDate(publishedTime, DateUtil.TIME_FORMAT);
			cmsInfo.setPublishDate(publishDate);
		}
		if(!StringUtils.isBlank(expDateStr) && !expDateStr.equals("?")){
			Date offDate = DateUtil.getDate(expDateStr, DateUtil.TIME_FORMAT);
			cmsInfo.setOffDate(offDate);
		}
		cmsInfo.setStatus("F");
		
		InfoDetail detail = new InfoDetail();
		detail.setFullTitle(info.getTitle());
		if(!StringUtils.isBlank(info.getUrl()) && !info.getUrl().equals("?")){
			detail.setLink(info.getUrl());
		}
		detail.setMetaDescription(info.getSource());
		detail.setTitle(info.getTitle());
		
		Integer nodeId=Integer.valueOf(cateID);
		String tagKeywords=null;
		Integer[] nodeIds=null;
		if(!StringUtils.isBlank(subCateIDs) && !subCateIDs.equals("?")){
			nodeIds = toIntArray(subCateIDs);
		}
		
		Integer[] specialIds=null;
		Integer[] viewGroupIds=null;
		Integer[] viewOrgIds=null;
		Map<String, String> customs = new HashMap<String, String>();//{text_editor_type=ueditor}
		Integer[] attrIds=null;
		Map<String, String> attrImages = new HashMap<String, String>();
		boolean draft=false;
		
		String[] imagesName = null;
		String[] imagesText = null;
		String[] imagesImage= null;
		
		
//		String[] filesName= new String[]{"正版化模板 (8).xls","集团正版化台账-12-14 -v1.xlsx"};
//		String[] filesFile=new String[]{"/itcms/uploads/5/file/public/201612/20161215201800_cwejv3g16g.xls","/itcms/uploads/5/file/public/201612/20161215201812_8es5g0vssn.xlsx"};
//		Long[] filesLength=new Long[]{21212l, 32345l};
		String[] filesName= null;
		String[] filesFile=null;
		Long[] filesLength=null;
		
		
		
		Map<String, String> clobs = new HashMap<String, String>();
		clobs.put("text", content);
		
		Info bean = save(cmsInfo, detail, nodeIds, specialIds, viewGroupIds, viewOrgIds, attrIds,nodeId, tagKeywords, draft, 
				imagesName, imagesText, imagesImage, filesName, filesFile, filesLength, customs, clobs, attrImages);
		if(!StringUtils.isBlank(filesJson) && !filesJson.equals("?")){
			Set<String> urls = new HashSet<String>();
			List<String> fileNames = new ArrayList<String>();
			List<AttachVO> list = JSONObject.parseArray(filesJson, AttachVO.class); 
			for (AttachVO attachVO : list) {
				String url = attachVO.getUrl();
				String fileName = attachVO.getFileName();
				urls.add(url);
				fileNames.add(fileName);
				Attachment attachment = attachmentService.save(url, fileName, 0l, "127.0.0.1", 1, 5);
				attachmentRefService.save(Info.ATTACH_TYPE, bean.getId(), attachment);
//				attachmentRefService.update(urls, Info.ATTACH_TYPE, bean.getId());
			}
		}
		return bean;
	}

	private Info setCustomsValue(InfoExt info) {
		String cateID = info.getCateID();
		String subCateIDs = info.getSubCateID();
		String content = info.getContent();
		String expDateStr = info.getExpDate();
		String publishedTime = info.getPublishedTime();
		String filesJson = info.getFilesJsoin();
		Info cmsInfo = new Info();
		if(!StringUtils.isBlank(publishedTime) && !publishedTime.equals("?")){
			Date publishDate = DateUtil.getDate(publishedTime, DateUtil.TIME_FORMAT);
			cmsInfo.setPublishDate(publishDate);
		}
		if(!StringUtils.isBlank(expDateStr) && !expDateStr.equals("?")){
			Date offDate = DateUtil.getDate(expDateStr, DateUtil.TIME_FORMAT);
			cmsInfo.setOffDate(offDate);
		}
		cmsInfo.setStatus("F");
		
		InfoDetail detail = new InfoDetail();
		detail.setFullTitle(info.getTitle());
		if(!StringUtils.isBlank(info.getUrl()) && !info.getUrl().equals("?")){
			detail.setLink(info.getUrl());
		}
		detail.setMetaDescription(info.getSource());
		detail.setTitle(info.getTitle());
		
		Integer nodeId=Integer.valueOf(cateID);
		String tagKeywords=null;
		Integer[] nodeIds=null;
		if(!StringUtils.isBlank(subCateIDs) && !subCateIDs.equals("?")){
			nodeIds = toIntArray(subCateIDs);
		}
		
		Integer[] specialIds=null;
		Integer[] viewGroupIds=null;
		Integer[] viewOrgIds=null;
		//Map<String, String> customs = new HashMap<String, String>();//{text_editor_type=ueditor}
		Map<String, String> customs = info.getCustoms();
		Integer[] attrIds=null;
		Map<String, String> attrImages = new HashMap<String, String>();
		boolean draft=false;
		
		String[] imagesName = null;
		String[] imagesText = null;
		String[] imagesImage= null;
		
		
//		String[] filesName= new String[]{"正版化模板 (8).xls","集团正版化台账-12-14 -v1.xlsx"};
//		String[] filesFile=new String[]{"/itcms/uploads/5/file/public/201612/20161215201800_cwejv3g16g.xls","/itcms/uploads/5/file/public/201612/20161215201812_8es5g0vssn.xlsx"};
//		Long[] filesLength=new Long[]{21212l, 32345l};
		String[] filesName= null;
		String[] filesFile=null;
		Long[] filesLength=null;
		
		Map<String, String> clobs = new HashMap<String, String>();
		clobs.put("text", content);
		
		Info bean = save(cmsInfo, detail, nodeIds, specialIds, viewGroupIds, viewOrgIds, attrIds,nodeId, tagKeywords, draft, 
				imagesName, imagesText, imagesImage, filesName, filesFile, filesLength, customs, clobs, attrImages);
		if(!StringUtils.isBlank(filesJson) && !filesJson.equals("?")){
			Set<String> urls = new HashSet<String>();
			List<String> fileNames = new ArrayList<String>();
			List<AttachVO> list = JSONObject.parseArray(filesJson, AttachVO.class); 
			for (AttachVO attachVO : list) {
				String url = attachVO.getUrl();
				String fileName = attachVO.getFileName();
				urls.add(url);
				fileNames.add(fileName);
				Attachment attachment = attachmentService.save(url, fileName, 0l, "127.0.0.1", 1, 5);
				attachmentRefService.save(Info.ATTACH_TYPE, bean.getId(), attachment);
//				attachmentRefService.update(urls, Info.ATTACH_TYPE, bean.getId());
			}
		}
		return bean;
	}
	/**
	 * 信息保存
	 * @return
	 */
	public Info save(Info bean, InfoDetail detail, Integer[] nodeIds,
			Integer[] specialIds, Integer[] viewGroupIds, Integer[] viewOrgIds,
			Integer[] attrIds, Integer nodeId, String tagKeywords,
			@RequestParam(defaultValue = "false") boolean draft,
			String[] imagesName, String[] imagesText, String[] imagesImage,
			String[] filesName, String[] filesFile, Long[] filesLength, 
			Map<String, String> customs, Map<String, String> clobs, Map<String, String> attrImages) {
		Integer siteId = 5;
		Integer userId = 1;
//		Integer siteId = Context.getCurrentSiteId();
//		Integer userId = Context.getCurrentUserId();
//		Map<String, String> customs = Servlets.getParamMap(request, "customs_");
//		Map<String, String> clobs = Servlets.getParamMap(request, "clobs_");
		if (StringUtils.isBlank(detail.getMetaDescription())) {
			String title = detail.getTitle();
			detail.setMetaDescription(Info.getDescription(clobs, title));
		}
		String[] tagNames = splitTagKeywords(tagKeywords);
//		Map<String, String> attrImages = Servlets.getParamMap(request,"attrImages_");
		for (Map.Entry<String, String> entry : attrImages.entrySet()) {
			entry.setValue(StringUtils.trimToNull(entry.getValue()));
		}
		List<InfoImage> images = new ArrayList<InfoImage>();
		if (imagesName != null) {
			InfoImage infoImage;
			for (int i = 0, len = imagesName.length; i < len; i++) {
				if (StringUtils.isNotBlank(imagesName[i])
						|| StringUtils.isNotBlank(imagesText[i])
						|| StringUtils.isNotBlank(imagesImage[i])) {
					infoImage = new InfoImage(imagesName[i], imagesText[i],
							imagesImage[i]);
					images.add(infoImage);
				}
			}
		}
		List<InfoFile> files = new ArrayList<InfoFile>();
		if (filesName != null) {
			InfoFile infoFile;
			for (int i = 0, len = filesFile.length; i < len; i++) {
				if (StringUtils.isNotBlank(filesName[i])
						&& StringUtils.isNotBlank(filesFile[i])) {
					infoFile = new InfoFile(filesName[i], filesFile[i],
							filesLength[i]);
					files.add(infoFile);
				}
			}
		}
		String status = draft ? Info.DRAFT : null;
		Info info = infoService.save(bean, detail, nodeIds, specialIds, viewGroupIds,
				viewOrgIds, customs, clobs, images, files, attrIds, attrImages,
				tagNames, nodeId, userId, status, siteId);
		logger.info("save Info, title={}.", bean.getTitle());
		return info;
	}
	
	private String[] splitTagKeywords(String tagKeywords) {
		String split = Constants.TAG_KEYWORDS_SPLIT;
		if (StringUtils.isNotBlank(split)) {
			for (int i = 0, len = split.length(); i < len; i++) {
				tagKeywords = StringUtils.replace(tagKeywords,
						String.valueOf(split.charAt(i)), ",");
			}
		}
		return StringUtils.split(tagKeywords, ',');
	}
	
	public List<Person> findAll(String name){  
        ArrayList<Person> persons = new ArrayList<Person>();  
        
        Person p1 = new Person();
        p1.setName(name + "3");
        p1.setAge(18);
        
        Person p2 = new Person();
        p2.setName(name + "4");
        p2.setAge(20);
        
        persons.add(p1);
        persons.add(p2);
        
        return persons;  
    }  
	
	public  int[] stringArrayToIntArray(String[] array){
	    int[] intArray = new int[array.length];
	    for(int i = 0; i < array.length; i++){
	        intArray[i] = Integer.parseInt(array[i]);
	    }
	    return intArray;
	}
	
	 /** 将data转化为1维整型数组, data形如："1,3,4,5,6" */  
    public Integer[] toIntArray(String data)  
    {  
        String[] datas = data.split(",");  
        Integer[] tmp = new Integer[datas.length];  
          
        for(Integer i=0; i<datas.length; i++)  
            tmp[i] = Integer.parseInt(datas[i]);  
          
        return tmp;  
    }  
    
	@Autowired
	private SiteService siteService;
	@Autowired
	private UserService userService;
	@Autowired
	private InfoService infoService;
	@Autowired
	private NodeQueryService query;
	@Autowired
	private OperationLogService logService;
	@Autowired
	private OrgService orgService;
	@Autowired
	private AttachmentRefService attachmentRefService;
	@Autowired
	private AttachmentService attachmentService;
	@Autowired
	private OANodeService oaNodeService;
}
